# views.py

import re
from datetime import datetime

from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect

from titiaccount.app.account.models import Account
from titiaccount.app.account.models import Transaction
from titiaccount.app.account.models import Tag

def index(request):
    return HttpResponseRedirect('list')

def list(request):
    try:
        user = request.session['user']
        accounts = Account.all_by_owner(user.email)
        types = []
        for account in accounts:
            if account.type not in types:
                types.append(account.type)
        
        tags = Tag.all_by_owner(user.email)
        tag_count = 0
        reset_tag = []
        for tag in tags:
            tag_count += tag.count
        for tag in tags:
            if float(tag.count) / float(tag_count) * 100.00 > 10.00:
                tag_type = 'big'
            elif float(tag.count) / float(tag_count) * 100.00 > 5.00:
                tag_type = 'normal'
            else:
                tag_type = 'small'
            reset_tag.append([tag, tag_type])

        return render_to_response('account/list.html', {'accounts': accounts, 'types': types, 'tags': reset_tag})
    except:
        return HttpResponseRedirect('/')
    
def new(request):
    try:
        user = request.session['user']
        if request.method == 'GET':
            return render_to_response('account/account.html', {'is_new': True})
        if request.method == 'POST':
            account = Account(
                    name = request.POST['name'],
                    type = request.POST['type'],
                    amount = 0.0,
                    owner = user.email,
            )
            account.put()
            return HttpResponseRedirect('list')
    except:
        return HttpResponseRedirect('/')

def edit(request):
    return render_to_response('account_new.html', {})

def delete(request):
    return render_to_response('account_new.html', {})

def reset_amount(request):
    try:
        user = request.session['user']
        accountId_pattern = re.compile('/account/(\d+)')
        accountId = int(accountId_pattern.findall(request.path)[0])
        account = Account.get_by_id(accountId)
        transaction_list = Transaction.all_by_account(account)

        amount = 0.0
        for transaction in transaction_list:
            if transaction.is_income:
                amount += transaction.amount
            else:
                amount -= transaction.amount
        account.amount = amount
        account.put()
        return HttpResponseRedirect('../list')
    except:
        return HttpResponseRedirect('/')

def trans_index(request):
    return HttpResponseRedirect('transaction/list')

def trans_list(request):
    try:
        user = request.session['user']
        accountId_pattern = re.compile('/account/(\d+)')
        pattern_list = accountId_pattern.findall(request.path)
        if pattern_list:
            accountId = int(pattern_list[0])
            account = Account.get_by_id(accountId)
        else:
            account = None

        tagId_pattern = re.compile('/tag/(\d+)')
        tag_list = tagId_pattern.findall(request.path)
        if tag_list:
            tag = Tag.get_by_id(int(tag_list[0]))
        else:
            tag = None

        # TODO: page_size need to get from client.
        if account:
            page_size = 20
        else:
            page_size = 5
        page = 1
        page_pattern = re.compile('/page/(\d+)$')
        pattern_list = page_pattern.findall(request.path)
        if pattern_list:
            page = int(pattern_list[0])

        try:
            request.GET['favorite']
            favorite = True
        except:
            favorite = False

        try:
            min_date = request.GET['min_date']
        except:
            min_date = None
        try:
            max_date = request.GET['max_date']
        except:
            max_date = None

        #if True:
        if request.is_ajax():
            if account:
                return HttpResponse(Transaction.all_by_account_json(account, tag, favorite, min_date, max_date, page = page, page_size = page_size), mimetype='text/plain')
            else:
                return HttpResponse(Transaction.all_by_owner_json(user.email, tag, favorite, min_date, max_date, page = page, page_size = page_size), mimetype='text/plain')
        else:
            return render_to_response('account/transaction/list.html', {'transactions': Transaction.all_by_account(account)})
    except:
        return HttpResponseRedirect('/')

def trans_new(request):
    try:
        user = request.session['user']
        if request.method == 'GET':
            return render_to_response('account/transaction/transaction.html', {'is_new': True})
        if request.method == 'POST':
            accountId_pattern = re.compile('/account/(\d+)')
            accountId = int(accountId_pattern.findall(request.path)[0])
            account = Account.get_by_id(accountId)

            trans_amount = float(request.POST['amount'])
            if request.POST['is_income'] == 'out':
                is_income = False
            else:
                is_income = True
            trans_date = datetime.strptime(request.POST['transaction_date'],'%Y-%m-%d')
            transaction = Transaction(
                    description = request.POST['description'],
                    amount = trans_amount,
                    account = account,
                    is_income = is_income,
                    tag = request.POST['tag'],
                    transaction_date = trans_date,
            )
            transaction.put()
            # Update Account Amount
            if is_income:
                account.amount = account.amount + transaction.amount
            else:
                account.amount = account.amount - transaction.amount
            account.put()

            # Update Tag Status 
            for tag_name in transaction.tag.split(','):
                if not Tag.is_exist(tag_name, user.email):
                    tag = Tag(
                            name = tag_name,
                            owner = user.email,
                            count = 1,
                    )
                else:
                    tag = Tag.get_by_name(tag_name, user.email)
                    tag.count = tag.count + 1
                tag.put()

            #if True:
            if request.is_ajax():
                return HttpResponse("200", mimetype='text/plain')
            else:
                return HttpResponseRedirect('list')
    except:
        return HttpResponseRedirect('/')

def trans_edit(request):
    try:
        user = request.session['user']
        if request.method == 'GET':
            return render_to_response('account/transaction/transaction.html', {'is_new': True})
        if request.method == 'POST':
            transactionId_pattern = re.compile('/(\d+)/edit$')
            transaction_id = int(transactionId_pattern.findall(request.path)[0])
            transaction = Transaction.get_by_id(transaction_id)

            # Update Account amount
            account = transaction.account
            if transaction.is_income:
                account.amount = account.amount - transaction.amount
            else:
                account.amount = account.amount + transaction.amount
            # Update Tag account
            if transaction.tag:
                for tag_name in transaction.tag.split(','):
                    tag = Tag.get_by_name(tag_name, user.email)
                    if tag:
                        tag.count = tag.count - 1
                        tag.put()

            transaction.description = request.POST['description']

            if request.POST['is_income'] == 'out':
                is_income = False
            else:
                is_income = True
            transaction.is_income = is_income
            transaction.amount = float(request.POST['amount'])
            transaction.tag = request.POST['tag']
            transaction.transaction_date = datetime.strptime(request.POST['transaction_date'],'%Y-%m-%d')
            transaction.put()

            if is_income:
                account.amount = account.amount + transaction.amount
            else:
                account.amount = account.amount - transaction.amount
            account.put()

            # Update Tag Status 
            for tag_name in transaction.tag.split(','):
                if not Tag.is_exist(tag_name, user.email):
                    tag = Tag(
                            name = tag_name,
                            owner = user.email,
                            count = 1,
                    )
                else:
                    tag = Tag.get_by_name(tag_name, user.email)
                    tag.count = tag.count + 1
                tag.put()

            #if True:
            if request.is_ajax():
                return HttpResponse("200", mimetype='text/plain')
            else:
                return HttpResponseRedirect('list')
    except:
        return HttpResponseRedirect('/')


def trans_delete(request):
    try:
        user = request.session['user']
        transactionId_pattern = re.compile('/(\d+)/delete$')
        transaction_id = int(transactionId_pattern.findall(request.path)[0])
        transaction = Transaction.get_by_id(transaction_id)

        if not transaction:
            return HttpResponseRedirect(str(transaction_id))
        # Update Account Amount
        account = transaction.account
        if transaction.is_income:
            account.amount = account.amount - transaction.amount
        else:
            account.amount = account.amount + transaction.amount
        account.put()
        # Update Tag Account
        if transaction.tag:
            for tag_name in transaction.tag.split(','):
                tag = Tag.get_by_name(tag_name, user.email)
                if tag:
                    tag.count = tag.count - 1
                    tag.put()

        transaction.delete()

        #if True:
        if request.is_ajax():
            return HttpResponse("200", mimetype='text/plain')
        else:
            return HttpResponseRedirect('../list')
    except:
        return HttpResponseRedirect('/')

def trans_favorite_on(request):
    try:
        user = request.session['user']
        transactionId_pattern = re.compile('/(\d+)/favorite_on$')
        transaction_id = int(transactionId_pattern.findall(request.path)[0])
        transaction = Transaction.get_by_id(transaction_id)

        if not transaction:
            return HttpResponseRedirect(str(transaction_id))

        transaction.favorite = True
        transaction.put()

        #if True:
        if request.is_ajax():
            return HttpResponse("200", mimetype='text/plain')
        else:
            return HttpResponseRedirect('../list')
    except:
        return HttpResponseRedirect('/')

def trans_favorite_off(request):
    try:
        user = request.session['user']
        transactionId_pattern = re.compile('/(\d+)/favorite_off$')
        transaction_id = int(transactionId_pattern.findall(request.path)[0])
        transaction = Transaction.get_by_id(transaction_id)

        if not transaction:
            return HttpResponseRedirect(str(transaction_id))

        transaction.favorite = False
        transaction.put()

        #if True:
        if request.is_ajax():
            return HttpResponse("200", mimetype='text/plain')
        else:
            return HttpResponseRedirect('../list')
    except:
        return HttpResponseRedirect('/')
